package org.nf.box.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.nf.box.domain.Comment;
import org.nf.box.domain.PersonalInfo;
import org.nf.box.domain.SubComments;
import org.nf.box.mapper.CommentLikeMapper;
import org.nf.box.mapper.CommentMapper;
import org.nf.box.mapper.SubCommentMapper;
import org.nf.box.service.CommentService;
import org.nf.box.service.PersonalInfoService;
import org.nf.box.service.SubCommentService;
import org.nf.box.web.vo.CommentVO;
import org.nf.box.web.vo.SubCommentVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @Author lzp
 * @Date 2024-12-19
 * 子评论业务
 */
@Service("subCommentService")
@RequiredArgsConstructor
@Transactional(rollbackFor = RuntimeException.class)
@Slf4j
public class SubCommentServiceImpl implements SubCommentService {

    private  final SubCommentMapper subCommentMapper;
    private final PersonalInfoService personalInfoService;

    @Override
    public void addComment(SubComments subComments) {
        subCommentMapper.addSubComment(subComments);
    }

    @Override
    public List<SubCommentVO> getSubComments(Integer parentId) {
        // 从数据库中获取指定parentId的所有子评论
        List<SubCommentVO> subComments = subCommentMapper.getSubComment(parentId);
        // 收集所有子评论的用户ID
        Set<Integer> userIds = subComments.stream()
                .map(SubCommentVO::getUserId)
                .collect(Collectors.toSet());

        // 批量获取个人信息
        Map<Integer, PersonalInfo> personalInfoMap = personalInfoService.getPointerInfosByIds(new ArrayList<>(userIds));

        // 为每个子评论设置信息
        for (SubCommentVO comment : subComments) {
            PersonalInfo personalInfo = personalInfoMap.get(comment.getUserId());
            if (personalInfo != null) {
                comment.setNickname(personalInfo.getNickName());
            }
            Integer likeCount = subCommentMapper.getLikeCount(comment.getSubCommentId());
            comment.setLikeCount(likeCount);
            Integer isLink = subCommentMapper.getIsLink(comment.getSubCommentId(), comment.getUserId());
            comment.setIsLink(isLink);
        }
        // 返回子评论列表
        return subComments;
    }


}
